//
//  RHBuyersViewController.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/12.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import URLNavigator
import SVProgressHUD

class RHBuyersViewController: RHViewController, UITableViewDelegate, UITableViewDataSource {
    
    var searchBarView: UIView?
    var tableView: RHTableView?
    var responseModel: RHBuyersDetailsResponseModel?
    private let navigator: NavigatorType = RHRouterNavigator.sharedInstance.navigator
    var imageArray = Array<UIImage>()
    var isRefresh = true
    var refreshController:UIRefreshControl?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("BuyersTitle", comment: "")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "app_icon_add"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(addData))
        
        loadTableView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isRefresh {
            loadClientsApi()
        }
        isRefresh = false
    }
    
    @objc func loadClientsApi(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doGetClients(pageNumber: "1", pageSize: "20", result: {[weak self] (msg, model) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.responseModel = model as? RHBuyersDetailsResponseModel
            weakSelf.loadImageView()
            weakSelf.refreshController?.endRefreshing()
            weakSelf.tableView?.reloadData()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            self.refreshController?.endRefreshing()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    @objc func addData() {
        isRefresh = true
        let vc = RHAddBuyersCustomersVC()
        vc.state = pageState.AddBuyersCustomers
        self.present(RHCustomNavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    
    func loadTableView() {
        self.tableView = RHTableView(frame: CGRect.zero, style: .plain)
        self.tableView?.delegate = self;
        self.tableView?.dataSource = self;
        self.tableView?.register(RHImageTableViewCell.self, forCellReuseIdentifier: "RHImageTableViewCell")
        self.view.addSubview(self.tableView!)
        
        refreshController = UIRefreshControl()
        tableView?.addSubview(refreshController!)
        //添加监听方法
        refreshController!.addTarget(self, action: #selector(loadClientsApi), for: .valueChanged)
        
        self.tableView?.snp.makeConstraints { [weak self](make) in
            guard let weakSelf = self else { return }
            make.top.equalTo(10)
            make.left.equalTo(weakSelf.view.snp.left)
            make.right.equalTo(weakSelf.view.snp.right)
            make.bottom.equalTo(weakSelf.view.snp.bottom)
        }
    }
    
    func addTapGesture(searchBar: UISearchBar){
        searchBar.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(searchBarClick))
        tapGesture.numberOfTapsRequired = 1
        searchBar.addGestureRecognizer(tapGesture)
    }
    
    @objc fileprivate func searchBarClick(){
        let searchVC = RHHousesSearchViewController()
        self.present(RHCustomNavigationController(rootViewController: searchVC), animated: false, completion: nil)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.responseModel == nil ? 0 : (self.responseModel?.data?.count)!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = RHAddBuyersCustomersVC()
        vc.state = pageState.ReadBuyersCustomers
        vc.clientId = self.responseModel?.data![indexPath.row].clientId
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: RHImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHImageTableViewCell", for: indexPath) as! RHImageTableViewCell
        cell.leftImageView?.image = imageArray[indexPath.row]
        cell.titleLabel?.text = self.responseModel?.data![indexPath.row].name
        cell.contentLabel?.text = self.responseModel?.data![indexPath.row].phone
        return cell
    }
    
    func loadImageView(){
        for item in (self.responseModel?.data)! {
            if item.photo != nil {
                let data = try? Data(contentsOf: URL(string: item.photo!)!)
                if data != nil {
                    imageArray.append(UIImage(data: data!)!)
                }else{
                    imageArray.append(UIImage(named: "placeholder")!)
                }
            }else{
                imageArray.append(UIImage(named: "placeholder")!)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.delete
    }
    
    //在这里修改删除按钮的文字
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return NSLocalizedString("DeleteText", comment: "")
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete {
            RHAPIManager.sharedInstance.doDeleteClients(clientId: (self.responseModel?.data![indexPath.row].clientId)!, result: { [weak self] (msg, model) in
                guard let weakSelf = self else { return }
                weakSelf.loadClientsApi()
            }) { (code, msg) in
            }
        }
    }
}
